//
//  PictureViewController.m
//  Qiubai
//
//  Created by Wu Dongyang on 13-5-30.
//  Copyright (c) 2013年 Wu Dongyang. All rights reserved.
//

#import "PictureViewController.h"
#import "QuartzCore/QuartzCore.h"

@interface PictureViewController ()<UIScrollViewDelegate, UIActionSheetDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UIImage *thumbImage;
@property (strong, nonatomic) NSString *largeImagePath;
@property (weak, nonatomic) UIView *fromImageView;
@property (assign, nonatomic) CGRect fromRect;

@property (assign, nonatomic) BOOL statusBarHidden;//记录出现之前的statusBar状态

@property (assign, nonatomic) BOOL didApear;//view是否出现，若未出现则不执行viewWillLayout
@property (assign, nonatomic) BOOL LayoutToBack;//是否是返回的那次，来调节imageView的位置
@property (assign, nonatomic) UIInterfaceOrientation viewInterfaceOrientation;//记录之前的方向

@property (strong, nonatomic) UITapGestureRecognizer *tap;
@end

static float animTime = 0.35;
@implementation PictureViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(id)initWithThumbImage:(UIImage *)image imageView:(UIView *)imageView largeImagePath:(NSString *)largeImagePath{
    self = [super init];
    @try {
        if (self) {
            self.thumbImage = image;
            self.largeImagePath = largeImagePath;
            self.fromImageView = imageView;
            //        self.fromRect = [imageView.superview convertRect:imageView.frame toView:self.contentBackView];
            
            //        UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
            //        [window addSubview:self.view];
            //        [self.view setFrame:window.bounds];
            
            self.window = [[UIWindow alloc] initWithFrame:[[[UIApplication sharedApplication] delegate] window].frame];
            self.window.windowLevel = UIWindowLevelStatusBar + 1.0f;
            self.window.hidden = NO;
            [self.window addSubview:self.view];
            [self.view setFrame:self.window.bounds];
        }
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        return self;
    }
    

    
}
#pragma mark - zoom
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView{
    
    @try {
        if (self.imageView.frame.size.width/self.imageView.frame.size.height >= self.contentScrollView.frame.size.width/self.contentScrollView.frame.size.height) {
            //image宽
            if (self.imageView.frame.size.height <= self.contentScrollView.frame.size.height) {
                CGRect frame = self.imageView.frame;
                frame.origin.y = (self.contentScrollView.frame.size.height - self.imageView.frame.size.height)/2;
                [self.imageView setFrame:frame];
            }else{
                CGRect frame = self.imageView.frame;
                frame.origin.y = 0;
                [self.imageView setFrame:frame];
            }
        }else{
            if (self.imageView.frame.size.width <= self.contentScrollView.frame.size.width) {
                CGRect frame = self.imageView.frame;
                frame.origin.x = (self.contentScrollView.frame.size.width - self.imageView.frame.size.width)/2;
                [self.imageView setFrame:frame];
            }else{
                CGRect frame = self.imageView.frame;
                frame.origin.x = 0;
                [self.imageView setFrame:frame];
            }
        }
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }

}
#pragma mark - Layout
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.0]];
    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    
    UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPressGr.minimumPressDuration = 1.0;
    [self.view addGestureRecognizer:longPressGr];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    
}
-(void)viewDidAppear:(BOOL)animated{
    @try {
        self.viewInterfaceOrientation = [[[[UIApplication sharedApplication] delegate] window] rootViewController].interfaceOrientation;
        [self setBeginStatus];//转成之前view的方向
        
        self.didApear = YES;
        self.LayoutToBack = NO;
        
        self.contentScrollView.zoomScale = 1;
        [self.contentScrollView addSubview:self.imageView];
        
        [self.imageView setFrame:self.fromRect];
        [self.imageView setImage:self.thumbImage];
        
        
        [UIView animateWithDuration:animTime animations:^{
            [self.view setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:1.0]];
            self.saveButton.alpha = 1;
        }completion:^(BOOL finished) {
            [self.view addGestureRecognizer:self.tap];
            if (self.largeImagePath) {
                [NSThread detachNewThreadSelector:@selector(loadLargeImage) toTarget:self withObject:nil];
            }
        }];
        //    if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft || [[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
        //        [self setTransformFromDeviceOrientation:(UIDeviceOrientation)self.viewInterfaceOrientation toDeviceOrientation:[[UIDevice currentDevice] orientation] animated:YES];
        //    }else{
        //        [UIView animateWithDuration:animTime animations:^{
        //            [self viewWillLayoutSubviews];
        //        }];
        //    }
        
        
        int orientationSupport = [[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:[[[UIApplication sharedApplication] delegate] window]];
        //    //NSLog(@"orientationSupport:%x",orientationSupport);
        //    //NSLog(@"nowOrientation:%x",[[UIApplication sharedApplication] statusBarOrientation]);
        //进一位，转为mask的那种位运算
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        if (orientation == UIDeviceOrientationUnknown || orientation ==  UIDeviceOrientationFaceUp || orientation ==  UIDeviceOrientationFaceDown) {
            orientation = (UIDeviceOrientation)self.viewInterfaceOrientation;
        }
        if (orientation == UIDeviceOrientationPortraitUpsideDown && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone && SupportPhoneUpSideDown == NO) {
            orientation = UIDeviceOrientationPortrait;
        }
        if (1 << orientation & orientationSupport) {
            [UIView animateWithDuration:animTime animations:^{
                [self viewWillLayoutSubviews];
            }];
        }else{
            //NSLog(@"orientation:%d",orientation);
            [self setTransformFromDeviceOrientation:(UIDeviceOrientation)self.viewInterfaceOrientation toDeviceOrientation:[[UIDevice currentDevice] orientation] animated:YES];
        }
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }

    

    
    
    //用了window之后不用了
//    self.statusBarHidden = [[UIApplication sharedApplication] isStatusBarHidden];
//    if (self.statusBarHidden == NO) {
//        [[UIApplication sharedApplication] 8:YES withAnimation:UIStatusBarAnimationFade];
//    }
}
-(void)setBeginStatus{
    @try {
        UIInterfaceOrientation beginOrientation = self.viewInterfaceOrientation;
        float degrees = 0;
        if (beginOrientation == UIDeviceOrientationPortrait) {
            degrees = 0.;
        }else if (beginOrientation == UIDeviceOrientationPortraitUpsideDown){
            degrees = 180.;
        }else if (beginOrientation == UIDeviceOrientationLandscapeLeft){
            degrees = 90.;
        }else if (beginOrientation == UIDeviceOrientationLandscapeRight){
            degrees = -90.;
        }
        CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(degrees / 180. * M_PI);
        [self.contentBackView setTransform:rotationTransform];
        [self.contentBackView setFrame:self.view.bounds];
        
        self.fromRect = [self.fromImageView.superview convertRect:self.fromImageView.frame toView:self.contentBackView];
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }

}
-(void)viewDidDisappear:(BOOL)animated{
    self.didApear = NO;
}

- (void)deviceOrientationDidChange:(NSNotification *)notification {
	if ([self.view.superview isKindOfClass:[UIWindow class]]) {
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        if (orientation != UIDeviceOrientationFaceUp && orientation != UIDeviceOrientationFaceDown && orientation != (UIDeviceOrientation)self.viewInterfaceOrientation) {
            //设备方向从某个状态到UIDeviceOrientationFaceUp后又回到之前的状态也会触发到这里，所以要加上orientation != (UIDeviceOrientation)self.viewInterfaceOrientation
            
            if (orientation == UIDeviceOrientationPortraitUpsideDown && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone && SupportPhoneUpSideDown == NO) {
                return;
            }
            
            [self setTransformFromDeviceOrientation:(UIDeviceOrientation)self.viewInterfaceOrientation toDeviceOrientation:orientation animated:YES];
        }
		
	} else {
		self.view.frame = self.view.superview.bounds;
	}
}
- (void)setTransformFromDeviceOrientation:(UIDeviceOrientation)fromOrientation toDeviceOrientation:(UIDeviceOrientation)toOrientation animated:(BOOL) animated{
    //NSLog(@"toOeientation:%d",toOrientation);
    float degrees = 0;
    if (toOrientation == UIDeviceOrientationPortrait) {
        degrees = 0.;
    }else if (toOrientation == UIDeviceOrientationPortraitUpsideDown){
        int orientationSupport = [[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:[[[UIApplication sharedApplication] delegate] window]];
        if (orientationSupport & UIInterfaceOrientationMaskPortraitUpsideDown || ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone && SupportPhoneUpSideDown)) {
            degrees = 180.;
            toOrientation = UIDeviceOrientationPortraitUpsideDown;
        }else{
            degrees = 0.;
            return;
        }
    }else if (toOrientation == UIDeviceOrientationLandscapeLeft){
        degrees = 90.;
    }else if (toOrientation == UIDeviceOrientationLandscapeRight){
        degrees = -90.;
    }else{
        //UIDeviceOrientationFaceUp || UIDeviceOrientationFaceDown
        return;
    }
    ////NSLog(@"degress:%f",degrees);
    
    CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(degrees / 180. * M_PI);
    
    CGRect frame = self.view.bounds;
    if (self.viewInterfaceOrientation == UIInterfaceOrientationPortrait || self.viewInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
        if (toOrientation == UIDeviceOrientationLandscapeLeft || toOrientation == UIDeviceOrientationLandscapeRight) {
            frame.size.width = self.view.bounds.size.height;
            frame.size.height = self.view.bounds.size.width;
            
            frame.origin.x = (self.view.bounds.size.width - frame.size.width)/2;
            frame.origin.y = (self.view.bounds.size.height - frame.size.height)/2;
        }
    }else{
        if (toOrientation == UIDeviceOrientationPortrait || toOrientation == UIDeviceOrientationPortraitUpsideDown) {
            frame.size.width = self.view.bounds.size.height;
            frame.size.height = self.view.bounds.size.width;
            
            frame.origin.x = (self.view.bounds.size.width - frame.size.width)/2;
            frame.origin.y = (self.view.bounds.size.height - frame.size.height)/2;
        }
    }
    self.viewInterfaceOrientation = toOrientation;
//    if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) {
//        self.viewInterfaceOrientation = UIInterfaceOrientationPortrait;
//    }
    
    
    if (animated) {
        [UIView animateWithDuration:animTime animations:^{
            [self.contentBackView setFrame:frame];
            [self.contentBackView setTransform:rotationTransform];
        }];
    }else{
        [self.contentBackView setTransform:rotationTransform];
    }
    
}
-(void)viewWillLayoutSubviews{
    if (self.didApear == NO) {
        return;
    }
    
    ////NSLog(@"self.contentBackView.frame2:%@",NSStringFromCGRect(self.contentBackView.frame));
    
    
    if (self.LayoutToBack) {
        //返回的时候，imageView已经从scrollView拿出来了，不受zoom影响
        if (self.fromImageView.superview) {
            //如果之前图片来源的imageView改变了，还能回去
            self.fromRect = [self.fromImageView.superview convertRect:self.fromImageView.frame toView:self.contentBackView];
        }else{
            self.fromRect = CGRectMake(self.contentScrollView.frame.size.width/2, self.contentScrollView.frame.size.height/2, 0, 0);
        }
        
        [self.imageView setFrame:self.fromRect];
        
    }else{
        [self.contentScrollView setZoomScale:1.0 animated:YES];
        [self.contentScrollView setContentSize:CGSizeZero];
        
        CGSize imageSize = self.imageView.image.size;
        
        if (imageSize.width/imageSize.height >= self.contentScrollView.frame.size.width/self.contentScrollView.frame.size.height) {
            //image宽
            CGRect frame = CGRectZero;
            frame.size.width = self.contentScrollView.frame.size.width;
            frame.size.height = imageSize.height/imageSize.width * frame.size.width;
            frame.origin.x = (self.contentScrollView.bounds.size.width - frame.size.width)/2;
            frame.origin.y = (self.contentScrollView.bounds.size.height - frame.size.height)/2;
            [self.imageView setFrame:frame];
        }else{
            CGRect frame = CGRectZero;
            frame.size.height = self.contentScrollView.frame.size.height;
            frame.size.width = imageSize.width/imageSize.height * frame.size.height;
            frame.origin.x = (self.contentScrollView.bounds.size.width - frame.size.width)/2;
            frame.origin.y = (self.contentScrollView.bounds.size.height - frame.size.height)/2;
            [self.imageView setFrame:frame];
        }
    }
}
-(void)viewDidLayoutSubviews{
    
}

-(void)back{
    [self.view removeGestureRecognizer:self.tap];
    
    //把imageView从scrollView中拿出来放到上面，忽略zoom的影响
    CGRect frame = [self.contentScrollView convertRect:self.imageView.frame toView:self.contentBackView];
    [self.imageView setFrame:frame];
    [self.contentBackView insertSubview:self.imageView belowSubview:self.saveButton];
    
    //用了window之后不用了
//    if (self.statusBarHidden == NO) {
//        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
//    }
    self.LayoutToBack = YES;
    
    if (self.viewInterfaceOrientation != [[[[UIApplication sharedApplication] delegate] window] rootViewController].interfaceOrientation) {
        [self setTransformFromDeviceOrientation:(UIDeviceOrientation)self.interfaceOrientation toDeviceOrientation:(UIDeviceOrientation)[[UIApplication sharedApplication] statusBarOrientation] animated:YES];
    }else{
        [UIView animateWithDuration:animTime animations:^{
            [self viewWillLayoutSubviews];
        }];
    }
    
    [UIView animateWithDuration:animTime animations:^{
        [self.view setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.0]];
        [self.saveButton setAlpha:0];
    }completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        if ([self.delegate respondsToSelector:@selector(PictureViewDidDismiss)]) {
            self.window.hidden = YES;
            self.window = nil;
            [self.delegate PictureViewDidDismiss];
        }
        
    }];
}
#pragma mark - function
static int tapCount = 0;
static NSTimer *tapTimer = nil;
static float doubleTapTime = 0.2f;
-(void)tap:(UITapGestureRecognizer *)tapGestureRecognizer{
    if (tapCount == 0) {
        tapTimer  = [NSTimer scheduledTimerWithTimeInterval:doubleTapTime target:self selector:@selector(onTimeNoTap) userInfo:nil repeats:NO];
        tapCount ++;
    }else if (tapCount == 1){
        [tapTimer invalidate];
        tapCount = 0;
        
        if (self.contentScrollView.zoomScale < 2) {
            [self.contentScrollView setZoomScale:2 animated:YES];
        }else{
            [self.contentScrollView setZoomScale:1 animated:YES];
        }
    }
}
-(void)onTimeNoTap{
    [self back];
    tapCount = 0;
}

-(void)loadLargeImage{
    @try {
        NSString *imageName = self.largeImagePath.lastPathComponent;
        NSString *tempImagePath = [NSTemporaryDirectory() stringByAppendingPathComponent:imageName];
        if ([[NSFileManager defaultManager] fileExistsAtPath:tempImagePath]) {
            UIImage *image = [UIImage imageWithContentsOfFile:tempImagePath];
            if (image) {
                [self.imageView setImage:image];
                return;
            }
        }
        
        
        NSURL *imageURL = [NSURL URLWithString:self.largeImagePath];
        NSData *data = [NSData dataWithContentsOfURL:imageURL];
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            //        CATransition *anim = [CATransition animation];
            //        anim.duration = 0.2f;
            //        anim.type = kCATransitionFade;
            [self.imageView setImage:image];
            [data writeToFile:tempImagePath atomically:YES];
            //[self.imageView.layer addAnimation:anim forKey:nil];
        }
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }

}
//- (void)longPressToDo:(UILongPressGestureRecognizer *)tap
//{
//    [self.saveDoneLabel.layer setCornerRadius:10.];
//    
//    UIImage *image = self.imageView.image;
//    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//}
- (void)longPressToDo:(UILongPressGestureRecognizer *)tap
{
    if (tap.state == UIGestureRecognizerStateBegan) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"保存到手机", nil];
        [actionSheet showInView:self.view];
    }
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self.saveDoneLabel.layer setCornerRadius:10.];
        
        UIImage *image = self.imageView.image;
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
}
-(void)savePic:(id)sender{
    [self.saveDoneLabel.layer setCornerRadius:10.];
    
    UIImage *image = self.imageView.image;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    [UIView animateWithDuration:0.3f animations:^{
        self.saveButton.alpha = 0;
        self.saveDoneLabel.alpha = 1;
    }completion:^(BOOL finished) {
        [NSTimer scheduledTimerWithTimeInterval:0.8f target:self selector:@selector(hideDoneLabel) userInfo:nil repeats:NO];
    }];
}
-(void)hideDoneLabel{
    [UIView animateWithDuration:0.3f animations:^{
        self.saveDoneLabel.alpha = 0;
    }];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setContentScrollView:nil];
    [self setImageView:nil];
    [self setContentBackView:nil];
    [self setSaveButton:nil];
    [self setSaveDoneLabel:nil];
    [super viewDidUnload];
}
@end
